<?php
/**
 * Created by PhpStorm.
 * User: huutuit
 * Date: 10/29/2014
 * Time: 3:16 PM
 */

class Utility {
    private $path;

    public function __construct($options) {
        if (isset($options['path'])) {
            $this->path = $options['path'];
        }
    }

    /**
     * @param $dirName
     * @return bool
     */
    public static function deleteDirectory($dirName) {
        if (is_dir($dirName)) {
            $dir_handle = opendir($dirName);

            if (!$dir_handle) {
                return false;
            } else {
                while($file = readdir($dir_handle)) {
                    if ($file != "." && $file != "..") {
                        if (!is_dir($dirName."/".$file))
                            unlink($dirName."/".$file);
                        else
                            self::deleteDirectory($dirName.'/'.$file);
                    }
                }
            };

            closedir($dir_handle);
            rmdir($dirName);
        }

        return true;
    }

    /**
     * Copy folder
     * @param $sourcePath
     * @param $destinationPath
     * @return bool
     */
    public static function copyDirectory($sourcePath, $destinationPath) {
        if (is_dir($sourcePath)) {
            $dir_handle = opendir($sourcePath);

            if (!$dir_handle) {
                return false;
            } else {
                while($file = readdir($dir_handle)) {
                    if ($file != "." && $file != "..") {
                        if (!is_dir($sourcePath."/".$file)) {
                            if (!is_dir($destinationPath)) {
                                mkdir($destinationPath);
                            }

                            copy($sourcePath."/".$file, $destinationPath."/".$file);
                        } else {
                            self::copyDirectory($sourcePath.'/'.$file, $destinationPath.'/'.$file);
                        }
                    }
                }
            }

            closedir($dir_handle);
        }

        return true;
    }

    /**
     * @param $sourceFilePath
     * @param $destinationPath
     * @return bool
     */
    public static function generateThumbnail($sourceFilePath, $destinationPath) {
        $createdFlag = false;
        if (file_exists($sourceFilePath)) {
            $thumbMaxWidth  = Yii::app()->params['thumbnail']['thumb_max_width'];
            $thumbMaxHeight = Yii::app()->params['thumbnail']['thumb_max_height'];

            if (self::imageResize($sourceFilePath, $destinationPath, $thumbMaxWidth, $thumbMaxHeight)) {
                $createdFlag = true;
            }
        }

        return $createdFlag;
    }

    /**
     * @param $src
     * @param $dst
     * @param $width
     * @param $height
     * @param int $crop
     * @return bool
     */
    protected static function imageResize($src, $dst, $width, $height, $crop = 0)
    {
        if (!list($w, $h) = getimagesize($src)) return false;
        $type = strtolower(substr(strrchr($src, '.'), 1));

        switch($type) {
            case 'bmp':
                $img = imagecreatefromwbmp($src);
                $imageQuality = null;
                break;
            case 'gif':
                $img = imagecreatefromgif($src);
                $writeFunc = 'imagegif';
                $imageQuality = null;
                break;
            case 'jpg':
            case 'jpeg':
                $img = imagecreatefromjpeg($src);
                $writeFunc = 'imagejpeg';
                $imageQuality = 75;
                break;
            case 'png':
                $img = imagecreatefrompng($src);
                $writeFunc = 'imagepng';
                $imageQuality = 9;
                break;
            default :
                return false;
        }

        // resize
        if  ($crop) {
            if ($w < $width or $h < $height) {
                return copy($src, $dst);
            }

            $ratio = max($width/$w, $height/$h);
            $h = $height/$ratio;
            $x = ($w - $width/$ratio) / 2;
            $w = $width / $ratio;
        } else {
            if ($w < $width and $h < $height) {
                return copy($src, $dst);
            }

            $ratio  = min($width/$w, $height/$h);
            $width  = $w * $ratio;
            $height = $h * $ratio;
            $x = 0;
        }

        $new = imagecreatetruecolor($width, $height);
        // preserve transparency
        if ($type == 'gif' or $type == 'png') {
            imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
            imagealphablending($new, false);
            imagesavealpha($new, true);
        }

        if (imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h)) {
            return $writeFunc($new, $dst, $imageQuality);
        }

        return false;
    }

    /**
     * @param $model
     * @param array $data
     * @return bool
     */
    public static function copyImage(&$model, &$data = array()) {
        if ($model) {
            $uploadPath = public_path().'/'.Config::get('constants.UPLOAD.FOLDER_NAME');

            if (!file_exists($uploadPath)) {
                mkdir($uploadPath);
            } else {
                if (!file_exists($uploadPath.'/'.$data['product_folder_name'])) {
                    mkdir($uploadPath.'/'.$data['product_folder_name']);
                }
            }

            if (!file_exists($uploadPath.'/'.$data['product_folder_name'].'/'.$model->id)) {
                mkdir(($uploadPath.'/'.$data['product_folder_name'].'/'.$model->id));
            }

            if (!file_exists($uploadPath.'/'.$data['product_folder_name'].'/'.$model->id.'/thumbnail')) {
                mkdir(($uploadPath.'/'.$data['product_folder_name'].'/'.$model->id.'/thumbnail'));
            }

            $pathTmpMain = public_path().'/'.$data['image_main_path'];
            $pathMain = public_path().'/'.$model->product_image_main;
            $pathTmpThumbMain = public_path().'/'.$data['image_thumbnail_path'];
            $pathThumbMain = public_path().'/'.$model->product_image_thumbnail;

            if (file_exists($pathTmpMain) && is_file($pathTmpMain)) {
                copy($pathTmpMain, $pathMain);

                if(file_exists($pathTmpThumbMain)) {
                    copy($pathTmpThumbMain, $pathThumbMain);
                }
            } else {
                return false;
            }


            $path = public_path().'/'.Config::get('constants.UPLOAD.FOLDER_NAME').
                '/'.Config::get('constants.UPLOAD.PRODUCT_FOLDER_TMP_NAME')
                .'/'.session_id();

            self::deleteDirectory($path);

            return true;
        }

        return false;
    }
}